package sanshi.contect.compsite;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合模式，树状结构专用模式
 * 一个目录结构
 *
 *  root
 *     chapter1
 *      `    c11
 *           c12
 *     chapter2
 *           section21
 *                  c211
 *                  c212
 *  使用递归的方法进行遍历整个目录
 */
public class Main {
    public static void main(String[] args) {

        BranchNode root = new BranchNode("root");
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");

        LeafNode c11 = new LeafNode("c11");
        LeafNode c12 = new LeafNode("c12");

        BranchNode section21 = new BranchNode("section21");
        LeafNode c211 = new LeafNode("c211");
        LeafNode c212 = new LeafNode("c212");

        root.add(chapter1);
        root.add(chapter2);
        chapter1.add(c11);
        chapter1.add(c12);
        chapter2.add(section21);
        section21.add(c211);
        section21.add(c212);

        tree(root);

    }

    public static void tree(Node node){
        node.p();
        if (node instanceof BranchNode){
            for (Node node1 : ((BranchNode) node).nodes){
                tree(node1);
            }
        }
    }
}

/**
 * 节点
 */
abstract class Node{
    public abstract void p();
}

/**
 * 叶子
 */
class LeafNode extends Node{
    String content;

    public LeafNode(String content){
        this.content = content;
    }
    @Override
    public void p() {
        System.out.println(content);
    }
}

/**
 * 节点，可以有多个子节点
 */
class BranchNode extends Node{

    List<Node> nodes = new ArrayList<>();
    String name;
    public BranchNode(String name) {
        this.name = name;
    }
    @Override
    public void p() {
        System.out.println(name);
    }
    public void add(Node node){
        nodes.add(node);
    }
}
